// tcp客户端端的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <sys/fcntl.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <pty.h>
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
#include <mutex>
#include <sys/select.h>
#include <poll.h>
static struct termios new_settings;
static struct termios init_settings;
enum MessageType
{
    LOGIN,
    LOGOUT,
    POLL,
    SEND
};
char k = -1;
void init_keyboard()
{
    tcgetattr(0, &init_settings); // 读取原始配置信息
    new_settings = init_settings;

    //	new_settings.c_lflag |= ICANON;		// 启用标准输入处理，需要回车结束输入
    new_settings.c_lflag &= (~ICANON); // 不启用标准输入处理，屏蔽整行缓存，不需要回车，输入单个字符即可输出

    // new_settings.c_lflag |= ECHO; // 启动输入字符的本地回显功能
    new_settings.c_lflag &= (~ECHO); // 不启动输入字符的本地回显功能

    new_settings.c_lflag |= ISIG; // 启动信号
    // new_settings.c_cc[VTIME] = 0;
    // new_settings.c_cc[VMIN] = 1;
    tcsetattr(0, TCSANOW, &new_settings); // 设置新的配置信息
}
void nonStopAsk(int sockfd)
{
    while (true)
    {
        char inBuffer[3] = {0}, outBuffer[4096] = {0};
        // k = getchar();
        usleep(100 * 1000);
        // printf("%d",k);
        inBuffer[0] = POLL;
        write(sockfd, inBuffer, 1);
        int res = read(sockfd, outBuffer, 4095);
        if (res > 0)
        {
            if (outBuffer[0] != -1)
            {
                printf("%s",outBuffer);
                fflush(stdout);
            }
        }
    }
}
int main()
{
    // 1、创建socket套接字
    init_keyboard();
    // fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("socket error");
        return -1;
    }
    struct sockaddr_in ser;
    ser.sin_family = AF_INET;
    ser.sin_port = htons(atoi("8080"));
    ser.sin_addr.s_addr = inet_addr("127.0.0.1");
    socklen_t len = sizeof(struct sockaddr_in);
    if (connect(sockfd, (struct sockaddr *)&ser, len) < 0)
    {
        perror("connect error");
        return -1;
    }
    char buffer[1024] = {0};
    buffer[0] = LOGIN;
    write(sockfd, buffer, 1);
    read(sockfd, buffer, 1023);
    printf("id:%s\n", buffer);
    std::thread t(nonStopAsk, sockfd);
    t.detach();
    while (true)
    {
        k = getchar();
        char inBuffer[3] = {0};
        inBuffer[0] = SEND;
        inBuffer[1] = k;
        write(sockfd, inBuffer, 2);
    }
    t.~thread();
    close(sockfd);
    tcsetattr(0, TCSANOW, &init_settings); // 恢复原始配置信息
}